﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Xman.WebApi.Filters.Model;

namespace Xman.WebApi.Filters;

public static class FilterServiceCollectionExtensions
{
    public static IServiceCollection AddXmanFilters(this IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.Filters.Add<ApiResultFilterAttribute>();
            options.Filters.Add<CustomExceptionAttribute>();
        });
        services.Configure<ApiBehaviorOptions>(options =>
        {
            options.InvalidModelStateResponseFactory = context =>
            {
                var errors = context.ModelState.Keys.SelectMany(key =>
                {
                    return context.ModelState[key]?.Errors.Select(x => $"{key}:{x.ErrorMessage}") ?? new List<string>();
                }).ToList();
                return new ValidationResult(string.Join(",", errors));
            };
        });
        return services;
    }
}
